<%@page import="org.apache.log4j.Logger"%>
<%@page import="it.trekker.prefetch.IExcursionDAOWithPrefetch"%>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="it.trekker.dao.*" %>
<%@ page import="java.util.*" %>

<%!
String printTime(long time) {
	long hours = time/(1000*60*60);
	long minutes = time/(1000*60) - hours*60;
	long seconds = time/1000 - hours*60*60 - minutes*60;
	String hours_str;
	String minutes_str;
	String seconds_str;
	
	if(hours < 10) {
		hours_str = "0" + hours;
	}
	else {
		hours_str = String.valueOf(hours);
	}
	
	if(minutes < 10) {
		minutes_str = "0" + minutes;
	}
	else {
		minutes_str = String.valueOf(minutes);
	}
	
	if(seconds < 10) {
		seconds_str = "0" + seconds;
	}
	else {
		seconds_str = String.valueOf(seconds);
	}
	
	return new String(hours_str + ":" + minutes_str + ":" + seconds_str);
}
%>

<%
Logger logger = Logger.getLogger("it.trekker.excursion_details.jsp");

	//******* Initialize session *******//

IExcursionDAOWithPrefetch excursionDAO = (IExcursionDAOWithPrefetch)session.getValue("excursionDAO");
IExcursionCoordinateDAO excursionCoordinateDAO = (IExcursionCoordinateDAO)session.getValue("excursionCoordinateDAO");
IPoiDAO poiDAO = (IPoiDAO)session.getValue("poiDAO");
IPhotoDAO photoDAO = (IPhotoDAO)session.getValue("photoDAO");

// If ejb session beans are null create them
DAOFactory daoFactory = DAOFactory.getDAOFactory(application.getInitParameter("dao"));
if(excursionDAO == null) {
	excursionDAO = daoFactory.getExcursionDAOWithPrefetch();
	
	// Configure ExcursionDAOWithPrefetch
	double searchingRadius = Integer.parseInt(application.getInitParameter("searching_radius"));
	boolean cacheEnabled = Boolean.parseBoolean(application.getInitParameter("cache_enabled"));
	excursionDAO.setSearchingRadius(searchingRadius);
	excursionDAO.setCacheEnabled(cacheEnabled);
}
if(excursionCoordinateDAO == null) {
	excursionCoordinateDAO = daoFactory.getExcursionCoordinateDAO();
}
if(poiDAO == null) {
	poiDAO = daoFactory.getPoiDAO();
}
if(photoDAO == null) {
	photoDAO = daoFactory.getPhotoDAO();
}

// Save ejb session beans in session object
session.putValue("excursionDAO", excursionDAO);
session.putValue("excursionCoordinateDAO", excursionCoordinateDAO);
session.putValue("poiDAO", poiDAO);
session.putValue("photoDAO", photoDAO);

// Create excursion object to trace the excursion
Excursion excursion;
%>

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	
		<link rel="StyleSheet" href="styles/default.css" type="text/css" media="all" />
		
		<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
		<script type="text/javascript">
			function initialize() {
				<%
				int excursionId = Integer.parseInt(request.getParameter("id"));
				excursion = excursionDAO.findExcursionById(excursionId, true);
				/* excursionDAO.loadCache(excursion); */
				
				// Retrieve coordinates for the excursion  
				
				List<ExcursionCoordinate> locations;
				if(excursion != null) {
					/* locations = excursionCoordinateDAO.findCoordinateByExcursion(excursion); */
					locations = new ArrayList<ExcursionCoordinate>(excursion.getCoordinates());
				}
				else {
					locations = new ArrayList<ExcursionCoordinate>();
				}
				%>
				
				<%
				GPSCoordinate startCoord = new GPSCoordinate();
				int zoomLev;
				if(locations.size() > 0) {
					startCoord.setLatitude(locations.get(0).getCoordinate().getLatitude());
					startCoord.setLongitude(locations.get(0).getCoordinate().getLongitude());
					zoomLev = 12;
				}
				else {	// Roma
					startCoord.setLatitude(41.9109);
					startCoord.setLongitude(12.4818);
					zoomLev = 3;
				}
				%>
				
				var startPos = new google.maps.LatLng(<%= startCoord.getLatitude() %>, <%= startCoord.getLongitude() %>);
				var myOptions = {
					zoom : <%= zoomLev %>,
					center : startPos,
					mapTypeId : google.maps.MapTypeId.TERRAIN
				};
		
				var map = new google.maps.Map(document.getElementById("map_canvas"),
						myOptions);
		
				setPath(map);
				setStartEnd(map);
				setPoiMarkers(map);
				setCloseExcursionsMarkers(map);
			}
			
			function setPath(map) {
				var pathCoordinates = new google.maps.MVCArray();
				<% for (ExcursionCoordinate loc : locations) { %>
					var location = new google.maps.LatLng(<%= loc.getCoordinate().getLatitude() %>, <%= loc.getCoordinate().getLongitude() %>);
					pathCoordinates.push(location); 
				<% } %>
	
				
				var excursionPath = new google.maps.Polyline({
					path : pathCoordinates,
					strokeColor : "#FF0000",
					strokeOpacity : 1.0,
					strokeWeight : 2
				});
		
				excursionPath.setMap(map);
			}
			
			function setStartEnd(map) {
				var imageStart = 'images/icon-route-start.png';
				var imageEnd = 'images/icon-route-end.png';
				<%
				if(locations.size() >= 2) {
					GPSCoordinate startPoint = new GPSCoordinate();
					GPSCoordinate endPoint = new GPSCoordinate();
					
					/* startPoint.setLatitude(locations.get(0).getLatitude());
					startPoint.setLongitude(locations.get(0).getLongitude()); */
					startPoint.setLatitude(excursion.getStartPoint().getLatitude());
					startPoint.setLongitude(excursion.getStartPoint().getLongitude());
					
					/* endPoint.setLatitude(locations.get(locations.size()-1).getLatitude());
					endPoint.setLongitude(locations.get(locations.size()-1).getLongitude()); */
					endPoint.setLatitude(excursion.getEndPoint().getLatitude());
					endPoint.setLongitude(excursion.getEndPoint().getLongitude());
				%>
					var startPos = new google.maps.LatLng(<%= startPoint.getLatitude() %>, <%= startPoint.getLongitude() %>);
					var endPos = new google.maps.LatLng(<%= endPoint.getLatitude() %>, <%= endPoint.getLongitude() %>);
					var contentInfoStart = "<h1>Start</h1><br />(<%= startPoint.getLatitude() %>, <%= startPoint.getLongitude() %>)";
					var contentInfoEnd = "<h1>End</h1><br />(<%= endPoint.getLatitude() %>, <%= endPoint.getLongitude() %>)";
					
					var poiMarkerStart = new google.maps.Marker({
					      position: startPos,
					      map: map,
					      clickable: true,
					      icon: imageStart,
					      title: "Start",
					      content: contentInfoStart
					});
					poiMarkerStart.info = new google.maps.InfoWindow({
					    content: contentInfoStart
					});
					google.maps.event.addListener(poiMarkerStart, 'click', function() {
						poiMarkerStart.info.setContent(this.content);
						poiMarkerStart.info.open(map, this);
					});
					
					var poiMarkerEnd = new google.maps.Marker({
					      position: endPos,
					      map: map,
					      clickable: true,
					      icon: imageEnd,
					      title: "End",
					      content: contentInfoEnd
					});
					poiMarkerEnd.info = new google.maps.InfoWindow({
					    content: contentInfoEnd
					});
					google.maps.event.addListener(poiMarkerEnd, 'click', function() {
						poiMarkerEnd.info.setContent(this.content);
						poiMarkerEnd.info.open(map, this);
					});
				<%
				}
				%>
				
			}
			
			function setPoiMarkers(map) {
				var image = 'images/poi_marker.png';
				<% 	List<Poi> pois = poiDAO.findPoisByExcursion(excursion); %>
				<%	for(Poi poi : pois) { %>
						var myLatLng = new google.maps.LatLng(<%= poi.getLocation().getLatitude() %>, <%= poi.getLocation().getLongitude() %>);
						var contentInfo = "<h1><%= poi.getFriendlyName() %></h1><br />(<%= poi.getLocation().getLatitude() %>, <%= poi.getLocation().getLongitude() %>)"
						var poiMarker = new google.maps.Marker({
						      position: myLatLng,
						      map: map,
						      clickable: true,
						      icon: image,
						      title: "<%= poi.getFriendlyName() %>",
						      content: contentInfo
						  });
						poiMarker.info = new google.maps.InfoWindow({
						    content: contentInfo
						});
						google.maps.event.addListener(poiMarker, 'click', function() {
							poiMarker.info.setContent(this.content);
							poiMarker.info.open(map, this);
						});

				<%	} %> 
			}
			
			/* TODO: refactoring per incorporare GPSCoordinate in Photo*/
			
			<%-- function setPhotoMarkers(map) {
				var image = 'images/photo_marker.png';
				<% 	List<Photo> photos = photoDAO.findPhotosByExcursion(excursion); %>
				<%	for(Photo photo : photos) { %>
						var myLatLng = new google.maps.LatLng(<%= photo.getLatitude() %>, <%= photo.getLongitude() %>);
						var contentInfo = "<h1><%= photo.getId() %></h1><br />(<%= photo.getLatitude() %>, <%= photo.getLongitude() %>)"
						var poiMarker = new google.maps.Marker({
						      position: myLatLng,
						      map: map,
						      clickable: true,
						      icon: image,
						      title: "<%= photo.getId() %>",
						      content: contentInfo
						  });
						poiMarker.info = new google.maps.InfoWindow({
						    content: contentInfo
						});
						google.maps.event.addListener(poiMarker, 'click', function() {
							poiMarker.info.setContent(this.content);
							poiMarker.info.open(map, this);
						});

				<%	} %> 
			} --%>
			
			function setCloseExcursionsMarkers(map) {
				var image = 'images/other_excursion.png';
				<% 
				List<Excursion> closedExcursions = excursionDAO.findCloseExcursions(excursion);
				if(closedExcursions == null)	// if findCloseExcursion() returns null create an empty list
					closedExcursions = new ArrayList<Excursion>();
				for(Excursion exc : closedExcursions) {
						/* if(exc.getCoordinates().size() > 0) {
							List<GPSCoordinate> coordinates = new ArrayList<GPSCoordinate>(exc.getCoordinates());
							GPSCoordinate startPoint = coordinates.get(0); */
						GPSCoordinate startPoint = exc.getStartPoint();
						if(startPoint != null) {
						%>
							var myLatLng = new google.maps.LatLng(<%= startPoint.getLatitude() %>, <%= startPoint.getLongitude() %>);
							var contentInfo = '<h1><a href="excursion_details.jsp?id=<%= exc.getId() %>"><%= exc.getName() %></a></h1> (user: <%= exc.getUser().getUsername() %>)<br />(<%= startPoint.getLatitude() %>, <%= startPoint.getLongitude() %>)'
							var poiMarker = new google.maps.Marker({
							      position: myLatLng,
							      map: map,
							      clickable: true,
							      icon: image,
							      title: "<%= exc.getName() %>",
							      content: contentInfo,
							      excursionId: "<%= exc.getId() %>",
							      excursionName: "<%= exc.getName() %>"
							      
							  });
							poiMarker.info = new google.maps.InfoWindow({
							    content: contentInfo
							});
							google.maps.event.addListener(poiMarker, 'click', function() {
								poiMarker.info.setContent(this.content);
								poiMarker.info.open(map, this);
							});
						<% 
						} 
						%>
				<%	
				} 
				%> 
			}
		</script>
		<title>Excursion details</title>
	</head>
	
	<body onload="initialize()">
		<div id="menu_link">
				<a href="index.jsp">Back to home</a>
		</div>
		<div id="details">
			<div class="details_content">
				<h1>Details</h1>
				<div class="details_element">
					<span class="header">Id: </span> <%= excursion.getId() %>
				</div>
				<div class="details_element">
					<span class="header">User: </span> <%= excursion.getUser().getUsername() %>
				</div>
				<div class="details_element">
					<span class="header">Name: </span> <%= excursion.getName() %>
				</div>
				<div class="details_element">
					<span class="header">Date: </span> <%= new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss").format(excursion.getDate()) %>
				</div>
				<div class="details_element">
					<span class="header">Distance: </span> <%= String.format("%.3f Km", excursion.getDistance()/1000) %>
				</div>
				<div class="details_element">
					<span class="header">Altitude diff.: </span> <%= String.format("%.2f m", excursion.getTotAltitudeDifference()) %>
				</div>
				<div class="details_element">
					<span class="header">Mean pace: </span> <%= String.format("%.2f m/s", excursion.getMeanPace()) %>
				</div>
				<div class="details_element">
					<span class="header">Time: </span> <%= printTime(excursion.getTime()) %>
				</div>
				<div class="details_element">
					<span class="header">Steps: </span> <%= excursion.getSteps() %>
				</div>
			</div>
		</div>
		
		<div id="map">
			<h1>Map</h1>		
			<div id="map_canvas" style="width:100%; height:100%"></div>
		</div>
	</body>
</html>